const typeWiter = {
	queue: [],
	consuming: false,
	timmer: {},
	onConsume: {},
	setComsume(consumer) {
		this.onConsume = consumer;
	},

	dynamicSpeed() {
		const speed = 2000 / this.queue.length;
		if (speed > 200) {
			return 200;
		}
		return speed;
	},
	add(msg) {
		if (!msg) return;
		this.queue.push(...msg.split(""));
	},
	consume() {
		if (this.queue.length > 0) {
			const msg = this.queue.shift();
			msg & this.onConsume(msg);
		}
	},
	next() {
		this.consume();
		this.timmer = setTimeout(() => {
			this.consume();
			if (this.consuming) {
				this.next();
			}
		}, this.dynamicSpeed());
	},
	start() {
		this.consuming = true;
		this.next();
	},
	done() {
		this.consuming = false;
		clearTimeout(this.timmer);

		this.onConsume(this.queue.join(""));
		this.queue = [];
	},
};

export default typeWiter;
